import '../utils/http/http_client.dart';
import '../models/alert_log_model.dart';
import 'package:flutter/foundation.dart';
import 'dart:math' show min;

/// 数据服务提供者
/// 提供设备数据、事件、告警等数据相关功能
class DataProvider {
  final HttpClient _httpClient = HttpClient();
  
  /// 不带任何参数获取所有告警日志
  Future<AlertLogListResponse> getAllAlertLogs() async {
    try {
      debugPrint('==========================================================');
      debugPrint('DataProvider.getAllAlertLogs() - 开始执行');
      debugPrint('准备请求告警日志列表...');
      
      // 直接使用正确的URL
      String url = '/data/alert_log/list';
      debugPrint('告警日志请求URL: $url');
      debugPrint('使用的HttpClient实例: ${_httpClient.hashCode}');
      
      debugPrint('发送告警日志请求 - 开始');
      final response = await _httpClient.get(url);
      debugPrint('发送告警日志请求 - 完成');
      
      if (response != null) {
        debugPrint('告警日志请求成功，响应不为空');
        final responseStr = response.toString();
        final previewLength = min(100, responseStr.length);
        debugPrint('告警日志响应预览: ${responseStr.substring(0, previewLength)}...');
        
        if (response is Map<String, dynamic>) {
          debugPrint('响应是Map类型，代码: ${response['code']}');
          if (response['rows'] != null) {
            debugPrint('响应包含rows字段，数量: ${(response['rows'] as List?)?.length ?? 0}');
          } else {
            debugPrint('响应不包含rows字段');
          }
        } else {
          debugPrint('响应不是Map类型: ${response.runtimeType}');
        }
      } else {
        debugPrint('告警日志请求成功，但响应为空');
      }
      
      final result = AlertLogListResponse.fromJson(response);
      debugPrint('成功解析AlertLogListResponse，总记录数: ${result.total}');
      debugPrint('==========================================================');
      return result;
    } catch (e) {
      debugPrint('==========================================================');
      debugPrint('获取告警日志失败: $e');
      debugPrint('错误类型: ${e.runtimeType}');
      debugPrint('堆栈信息: ${StackTrace.current}');
      debugPrint('==========================================================');
      return AlertLogListResponse(
        code: 500, 
        msg: '请求失败: $e', 
        rows: [], 
        total: 0
      );
    }
  }
  
  /// 获取告警日志列表
  /// 
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  /// [deviceId] 设备ID（可选）
  /// [productKey] 产品标识码（可选）
  /// [deviceSn] 设备序列号（可选）
  /// [alertName] 告警名称（可选）
  /// [level] 严重级别(1:信息 2:警告 3:严重 4:紧急)（可选）
  /// [status] 状态(0:产生 1:恢复 2:已确认)（可选）
  /// [beginTime] 开始时间（可选）
  /// [endTime] 结束时间（可选）
  Future<AlertLogListResponse> getAlertLogList({
    int pageNum = 1,
    int pageSize = 10,
    int? deviceId,
    String? productKey,
    String? deviceSn,
    String? alertName,
    int? level,
    int? status,
    String? beginTime,
    String? endTime,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
      };
      
      // 添加可选参数
      if (deviceId != null) {
        params['deviceId'] = deviceId;
      }
      if (productKey != null && productKey.isNotEmpty) {
        params['productKey'] = productKey;
      }
      if (deviceSn != null && deviceSn.isNotEmpty) {
        params['deviceSn'] = deviceSn;
      }
      if (alertName != null && alertName.isNotEmpty) {
        params['alertName'] = alertName;
      }
      if (level != null) {
        params['level'] = level;
      }
      if (status != null) {
        params['status'] = status;
      }
      if (beginTime != null && beginTime.isNotEmpty) {
        params['beginTime'] = beginTime;
      }
      if (endTime != null && endTime.isNotEmpty) {
        params['endTime'] = endTime;
      }
      
      final response = await _httpClient.get(
        '/data/alert_log/list',
        params: params,
      );
      
      return AlertLogListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取告警日志详情
  /// 
  /// [logId] 日志ID
  Future<AlertLogDetailResponse> getAlertLogDetail(int logId) async {
    try {
      final response = await _httpClient.get('/data/alert_log/$logId');
      return AlertLogDetailResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 确认告警
  /// 
  /// [logId] 日志ID
  Future<bool> confirmAlertLog(int logId) async {
    try {
      final response = await _httpClient.put(
        '/data/alert_log/confirm/$logId',
      );
      return response['code'] == 200;
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取设备的告警日志列表
  /// 
  /// [deviceId] 设备ID
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  Future<AlertLogListResponse> getDeviceAlertLogs(
    int deviceId, {
    int pageNum = 1,
    int pageSize = 10,
    int? status,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
        'deviceId': deviceId,
      };
      
      if (status != null) {
        params['status'] = status;
      }
      
      final response = await _httpClient.get(
        '/data/alert_log/list',
        params: params,
      );
      
      return AlertLogListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取产品的告警日志列表
  /// 
  /// [productKey] 产品标识码
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  Future<AlertLogListResponse> getProductAlertLogs(
    String productKey, {
    int pageNum = 1,
    int pageSize = 10,
    int? status,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
        'productKey': productKey,
      };
      
      if (status != null) {
        params['status'] = status;
      }
      
      final response = await _httpClient.get(
        '/data/alert_log/list',
        params: params,
      );
      
      return AlertLogListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取未确认告警总数
  Future<int> getUnconfirmedAlertCount() async {
    try {
      final response = await _httpClient.get(
        '/data/alert_log/count/unconfirmed',
      );
      
      if (response['code'] == 200 && response['data'] != null) {
        return response['data'] as int;
      }
      
      return 0;
    } catch (e) {
      return 0;
    }
  }
  
  /// 获取最近24小时的告警日志统计
  Future<Map<String, int>> getRecentAlertStats() async {
    try {
      final response = await _httpClient.get(
        '/data/alert_log/stats/recent',
      );
      
      if (response['code'] == 200 && response['data'] != null) {
        final Map<String, dynamic> rawData = response['data'];
        return {
          'info': rawData['info'] ?? 0,
          'warning': rawData['warning'] ?? 0,
          'critical': rawData['critical'] ?? 0,
          'urgent': rawData['urgent'] ?? 0,
          'total': rawData['total'] ?? 0,
        };
      }
      
      return {
        'info': 0,
        'warning': 0,
        'critical': 0,
        'urgent': 0,
        'total': 0,
      };
    } catch (e) {
      return {
        'info': 0,
        'warning': 0,
        'critical': 0,
        'urgent': 0,
        'total': 0,
      };
    }
  }
} 